﻿
using Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls.WebParts;
using wnet.admin.wentcommon;
using static Org.BouncyCastle.Math.EC.ECCurve;

namespace wnet.admin
{
    /// <summary>
    /// 数据库工厂
    /// </summary>
    public class SqlSugarConfig
    {
        public static ISqlSugarClient CreateClient()
        {
            var db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = SqlSugar.DbType.MySql,
                IsAutoCloseConnection = true,
                ConnectionString = Config.ConnectionString,

            });


            //db.CodeFirst.InitTables(typeof(sys_user));



            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                string log = $"【db SQL语句】dbo.{sql} {string.Join(", ", pars.Select(x => x.ParameterName + " = " + GetParsValue(x)))};\n";
                LogHelper.WriteLog("sql=" + log);
            };

            return db;
        }
        private static object GetParsValue(SugarParameter x)
        {
            if (x.DbType == System.Data.DbType.String || x.DbType == System.Data.DbType.DateTime || x.DbType == System.Data.DbType.String)
            {
                return "'" + x.Value + "'";
            }
            return x.Value;
        }
    }

    /// <summary>
    /// 使用单例模式注册 ISqlSugarClient
    /// </summary>
    public static class SqlSugarClientManager
    {
        private static readonly object _lock = new object();
        private static ISqlSugarClient _sqlSugarClient;

        // 静态构造函数，在类首次加载时执行
        static SqlSugarClientManager()
        {
            InitializeSqlSugarClient();
        }

        private static void InitializeSqlSugarClient()
        {
            if (_sqlSugarClient == null)
            {
                lock (_lock)
                {
                    if (_sqlSugarClient == null)
                    {
                        // 创建 SqlSugar 客户端实例
                        var dbConfig = new ConnectionConfig()
                        {
                            ConnectionString = Config.ConnectionString,
                            DbType = DbType.MySql, // 根据您的数据库类型设置
                            IsAutoCloseConnection = true
                        };

                        _sqlSugarClient = new SqlSugarClient(dbConfig);
                    }
                }
            }
        }

        public static ISqlSugarClient GetInstance()
        {
            return _sqlSugarClient;
        }
    }
}